﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TorrentService;
using log4net;
using System.IO;
using System.Text.RegularExpressions;
using System.Net;
using System.Xml;
using MonoTorrent.Client;
using MonoTorrent.Common;
using System.Threading;
using XmlSettings;

namespace BotTorrent
{
  public class RssFeedManager
{
    // Fields
    public BitTorrentClient BTClient;
    public ircbot IrcBot;
    private static readonly ILog log = LogManager.GetLogger(typeof(BotTorrent));
    public Settings Settings;

    // Methods
    private void AddToHistory(string title)
    {
        try
        {
            if (!File.Exists("rsshistory.dat"))
            {
                File.Create("rsshistory.dat");
            }
            StreamWriter writer = File.AppendText("rsshistory.dat");
            writer.WriteLine(title);
            writer.Flush();
            writer.Close();
        }
        catch (Exception)
        {
        }
    }

    private bool CheckHistory(string title)
    {
        if (!File.Exists("rsshistory.dat"))
        {
            return false;
        }
        try
        {
            StreamReader reader = File.OpenText("rsshistory.dat");
            string linetext = null;
            while ((linetext = reader.ReadLine()) != null)
            {
                if (linetext == title)
                {
                    reader.Close();
                    return true;
                }
            }
            reader.Close();
            return false;
        }
        catch (Exception)
        {
            return false;
        }
    }

    public void DownloadFeeds()
    {
        foreach (RssFeed feed in this.Settings.RssFeeds)
        {
            if (!feed.Enabled)
                continue;

            try
            {
                log.Info("Checking RSS feed " + feed.Url);
                Regex regex = new Regex(feed.Filter);
                WebClient get = new WebClient();
                string feedData = null;
                feedData = get.DownloadString(feed.Url);
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(feedData);
                XmlNodeList nodes = doc.SelectNodes("//channel/item");
                foreach (XmlNode node in nodes)
                {
                    string title = node["title"].InnerText;
                    string link = node["link"].InnerText;
                    if (regex.IsMatch(title) && !this.CheckHistory(title))
                    {
                        log.Debug("Regex match on " + title);
                        string localtorrent = miscFunctions.DownloadFile(link, this.Settings);
                        this.AddToHistory(title);
                        if (this.BTClient.TorrentList.Count < this.Settings.TorrentSettings.MaxSimultaneousTorrents)
                        {
                            TorrentManager manager = new TorrentManager(Torrent.Load(localtorrent), this.Settings.TorrentSettings.downloadsPath, this.BTClient.torrentDefaults);
                            this.BTClient.Register(manager);
                            this.BTClient.TorrentList.Add(manager);
                            manager.HashCheck(true);
                            manager.Start();
                            log.Info("Started torrent " + title + " via RSS");
                            miscFunctions.MessageChannel("Just downloaded " + title + " via RSS.", this.IrcBot);
                        }
                        else
                        {
                            log.Info("Too many torrents already running, not starting " + title);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                log.Error("Exception in RSS manager " + e.Message);
            }
        }
    }

    public void Start()
    {
        TimeSpan retrydelay = new TimeSpan(0, 30, 0);
        while (true)
        {
            foreach (RssFeed feed in this.Settings.RssFeeds)
            {
                try
                {
                    this.DownloadFeeds();
                }
                catch (Exception)
                {
                }
            }
            Thread.Sleep(retrydelay);
        }
    }
}

 

}
